package com.ocss.ocsscustomerserver.interceptor;
import com.ocss.ocsscustomerserver.tools.VerifyTokenUntil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.websocket.server.PathParam;
import java.util.Map;



/**
 * @Auther: lijiang
 * @Date: 2023-04-12 17:13
 * @Description: websocket握手前的拦截器设置
 */
@Component
public class ConnectInterceptor implements HandshakeInterceptor {

    @Autowired
    VerifyTokenUntil verifyTokenUntil;

    //建立连接前验证Token
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        String token = ((ServletServerHttpRequest) request).getServletRequest().getParameter("token");
        if (token == null) return  false;
        if (!verifyTokenUntil.verifyToken(token)) return  false;
        attributes.put("id", verifyTokenUntil.getIdByToken(token));
        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {

    }
}